package artid.com.arttogoa;

import java.util.List;

import android.Manifest;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.PixelFormat;
import android.hardware.Camera;
import android.hardware.Camera.AutoFocusCallback;
import android.hardware.Camera.CameraInfo;
import android.hardware.Camera.Size;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.view.Surface;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.TextView;

import artid.com.arttogoa.R;

import artid.com.arttogoa.util.BitmapUtil;
import artid.com.arttogoa.util.NetUtils;
import artid.com.arttogoa.util.ToastUtil;

/**
 * 
 *    
 * 项目名称：ArtworkArtA   
 * 类名称   ：CustomCamera_Activity   
 * 类描述   ：拍摄艺术家真实照（自定义照相机）   
 * 创建人   ：耿卫斌   
 * 创建时间：2016-12-22 上午10:28:42   
 *	注释：当用完照片之后请删除
 */
@SuppressLint("NewApi") 
public class CustomCamera_Activity extends BaseActivity implements OnClickListener{
	private Context mContext;
	private Camera mCamera = null;
	private SurfaceView mSurfaceView;
	private SurfaceHolder surfaceHolder;
	private TextView submit;
	private int Degrees;//要旋转的图片角度
	private Boolean isSave=false;//记录是否已经拍照保存
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_customcamera);
		initView();
	}

	private void initView(){
		setContent(this, getIntent());
		setBack();
		mTittle.setText("自定义拍照");
		mContext=CustomCamera_Activity.this;
		TextView title_right=(TextView) findViewById(R.id.title_right);
		title_right.setText("提交审核");
		title_right.setOnClickListener(this);
		title_right.setVisibility(View.VISIBLE);
		mSurfaceView = (SurfaceView) findViewById(R.id.CustomCamera_surfaceView);
		submit=(TextView) findViewById(R.id.CustomCamera_submit);
		submit.setOnClickListener(this);
		checkCameraHardware(mContext);
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.CustomCamera_submit:
			if(isSave!=true){
				TakePhoto();
			}else{
				submit.setText("拍照");
				isSave=false;
				mCamera.startPreview();
			}
			break;
		default:
			break;
		}
	}

	private boolean checkCameraHardware(Context context) {
		if (context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA)){
			// this device has a camera  
			CallCamera();
			return true;  
		} else {  
			// no camera on this device  
			ToastUtil.toast(mContext, "您的设备不支持拍照");
			return false;  
		}  
	}  

	/**
	 * 调用照相机
	 */
	@SuppressWarnings("deprecation")
	private void CallCamera() {
		surfaceHolder = mSurfaceView.getHolder(); // 相机接口
		surfaceHolder.setKeepScreenOn(true);// 屏幕常亮  
		surfaceHolder.setFixedSize(mSurfaceView.getWidth(), mSurfaceView.getHeight());
		surfaceHolder.addCallback(surfaceCallback); // 添加一个回调的
		surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
	}

	// 开启照相机
	SurfaceHolder.Callback surfaceCallback = new SurfaceHolder.Callback() {

		public void surfaceCreated(SurfaceHolder holder) {
			try {
				int cameraCount = 0;
				CameraInfo cameraInfo = new CameraInfo();
				cameraCount = Camera.getNumberOfCameras();//得到摄像头的个数
				for(int i = 0; i < cameraCount; i++  ) {
					Camera.getCameraInfo(i, cameraInfo);//得到每一个摄像头的信息
					//现在是后置，变更为前置
					if(cameraInfo.facing  == Camera.CameraInfo.CAMERA_FACING_FRONT) {//代表摄像头的方位，CAMERA_FACING_FRONT前置      CAMERA_FACING_BACK后置  
						mCamera = Camera.open(i);//打开当前选中的摄像头
						mCamera.setPreviewDisplay(holder); // 设置预览
						initCamera();
					}
				}
			} catch (Exception e) {
				mCamera = null;
				displayFrameworkBugMessageAndExit();
			}
		}

		@Override
		public void surfaceChanged(SurfaceHolder holder, int format, final int width,
				final int height) {
			if (mCamera != null) {
				mCamera.autoFocus(new AutoFocusCallback() {
					@Override
					public void onAutoFocus(boolean success, Camera camera) {
						if (success) {
							Camera.Parameters parameters = mCamera.getParameters(); // 获取照相机
							initCamera();
							camera.cancelAutoFocus();
						}
					}
				});
			}
		}

		// 拍照状态变化时调用该方法
		@TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
		@SuppressWarnings("deprecation")
		private void initCamera() {
			try {
				Camera.Parameters parameters = mCamera.getParameters(); // 获取照相机
				parameters.setPictureFormat(PixelFormat.JPEG);// 设置照片
				parameters.setJpegQuality(100);
				setCameraResolution(parameters);
				mCamera.setParameters(parameters); // 设置照相机参数
				setCameraDisplayOrientation(CustomCamera_Activity.this, 0,mCamera);
				mCamera.startPreview(); // 启动预览
				mCamera.cancelAutoFocus();// 如果要实现连续的自动对焦，这一句必须加上
			} catch (Exception e) {
				// e.printStackTrace();
			}
		}

		// 停止拍照时调用该方法
		public void surfaceDestroyed(SurfaceHolder holder) {
			if (mCamera != null) {
				mCamera.stopPreview();// 停止预览
				mCamera.release(); // 释放相机资源
				mCamera = null;
			}
		}
	};

	// 提供一个静态方法，用于根据手机方向获得相机预览画面旋转的角度
	@TargetApi(Build.VERSION_CODES.GINGERBREAD)
	public  int setCameraDisplayOrientation(Activity activity,
			int cameraId, android.hardware.Camera camera) {
		android.hardware.Camera.CameraInfo info = new android.hardware.Camera.CameraInfo();
		android.hardware.Camera.getCameraInfo(cameraId, info);
		// 获得手机的方向
		int rotation = activity.getWindowManager().getDefaultDisplay().getRotation();
		int degrees = 0;
		// 根据手机的方向计算相机预览画面应该选择的角度
		switch (rotation) {
		case Surface.ROTATION_0:
			degrees = 0;
			break;
		case Surface.ROTATION_90:
			degrees = 90;
			break;
		case Surface.ROTATION_180:
			degrees = 180;
			break;
		case Surface.ROTATION_270:
			degrees = 270;
			break;
		}
		int result;
		if (info.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
			result = (info.orientation + degrees) % 360;
			result = (360 - result) % 360; // 补偿镜
		} else { // back-facing
			result = (info.orientation - degrees + 360) % 360;
		}
		camera.setDisplayOrientation(result);
		Degrees=-result;
		return result;
	}


	/**
	 * 拍照
	 */
	private void TakePhoto() {
		if (mCamera != null) {
			isSave=true;
			submit.setText("重拍");
			mCamera.takePicture(null, null, pictureCallback); // 拍照
		}
	}

	// 照相回调
	Camera.PictureCallback pictureCallback = new Camera.PictureCallback() {
		// @Override
		public void onPictureTaken(byte[] data, Camera camera) {
			if (camera != null) {
				playTone();
				camera.stopPreview();
				//进行拍照保存
				String path = Environment.getExternalStorageDirectory()+ "/YJB/realHeadImage.png";
				try {
					Bitmap mBitmap=	BitmapUtil.byteToBitmap(data);
					BitmapUtil.saveBitmapToFile(BitmapUtil.rotateBitmapByDegree(mBitmap, Degrees),path);
				} catch (Exception e) {
					// TODO Auto-generated catch block
					Log.d("log", "保存图片出错："+e.toString());
				}
			}
		}
	};

	// 设置拍照声音
	private void playTone() {
		MediaPlayer player = MediaPlayer.create(this, R.raw.takephoto);
		player.setAudioStreamType(AudioManager.STREAM_MUSIC);
		player.setVolume(0.5f, 0.5f);
		player.start();
	}

	private void setCameraResolution(Camera.Parameters parameters){
		try {
			List<Size> supportedPreviewSizes = parameters.getSupportedPreviewSizes(); 
			List<Size> supportedPictureSizes = parameters.getSupportedPictureSizes(); 
			for (int i = 0; i < supportedPreviewSizes.size(); i++) {
				if(supportedPreviewSizes.get(0).width>800){
					parameters.setPreviewSize(supportedPreviewSizes.get(0).width, supportedPreviewSizes.get(0).height);
				}else{
					parameters.setPreviewSize(supportedPreviewSizes.get(supportedPreviewSizes.size()).width, supportedPreviewSizes.get(supportedPreviewSizes.size()).height);
				}
			}
			for (int i = 0; i < supportedPictureSizes.size(); i++) {
				if(supportedPictureSizes.get(0).width>800){
					parameters.setPictureSize(supportedPictureSizes.get(0).width, supportedPictureSizes.get(0).height);
				}else{
					parameters.setPictureSize(supportedPictureSizes.get(supportedPictureSizes.size()).width, supportedPictureSizes.get(supportedPictureSizes.size()).height);
				}
			}
		} catch (Exception e) {
			// TODO: handle exception
		}
	}

	/**
	 * 若摄像头被占用或者摄像头有问题则跳出提示对话框
	 */
	private void displayFrameworkBugMessageAndExit() {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setTitle(getString(R.string.app_name));
		builder.setMessage("请设置开启摄像头权限");
		builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				NetUtils.getAppDetailSettingIntent(mContext);
			}
		});
		builder.show();
	}


	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		// 关闭当前页面时释放照相机
		if (mCamera != null) {
			mCamera.release(); // 释放照相机
			mCamera = null;
		}
	}

}
